﻿module app.handler.payment.alipay;

import app.handler.payment.base;
import std.json;
import app.helper.appinfo;
import std.datetime;
import std.experimental.logger;
import std.conv;
import std.typetuple;
import std.typecons;
import std.algorithm.sorting;
import app.service.paybillservice;
import app.model;
import core.stdc.time;


enum string ALIPAY_API_GATEWAY = "https://openapi.alipay.com/gateway.do";
enum string ALIPAY_CALLBACK_URL = "https://spay.putao.com/alipay/callbak/";

class AlipayHandler : PayHandlerBase
{
	string getAlipayMethod(){return "alipay.trade.app.pay";}
	string getAlipayProductCode(){return "QUICK_MSECURITY_PAY";}
	
	
	///创建订单并签名
	override string[string] createBillAndSign(out string bill_id)
	{
		string[string] channelConfig = getAppChannelConfig();
		if(channelConfig is null)
		{
			throwExceptionBuild!"NotSupportChannel"("NotSupportChannel : ");	
		}
		
		checkOutTradeNoIsPay();
		bill_id = saveBill();
		
		string[string] toSendAliData = [
			"app_id": channelConfig["appid"],//支付宝分配的
			"method":getAlipayMethod(),
			"format":"JSON",
			"charset":"utf-8",
			"sign_type" : "RSA2",
			"timestamp" : getTimeStamp(),
			"version":"1.0",
			"notify_url":ALIPAY_CALLBACK_URL ~orderJson["appid"].str ~"-" ~orderJson["channel"].str,
			"biz_content":getBusinessData(bill_id),
			"sign":"",
			"return_url":getReturnUrl()
		];
		string toSign = aaKsortSign(toSendAliData);
		import app.utils;
		toSendAliData["sign"] = rsa256SignPrivateKey(toSign, channelConfig["rsa_private_key"]);
		//return aaKsort4Alipay(toSendAliData, true);
		return toSendAliData;
	}
	
	///成功时候的跳转地址
	string getReturnUrl(){return "";}
	
	string getBusinessData(string bill_id){
		import std.uri;
		JSONValue jj = [
			"body" :orderJson["body"].str,
			"subject" :orderJson["subject"].str,
			"out_trade_no" :bill_id,
			"total_amount" : to!(string)(orderJson["amount"].integer/100.0),
			"product_code" :getAlipayProductCode(),
			"passback_params": encodeComponent( orderJson["appid"].str ~"@" ~orderJson["channel"].str~"@" ~orderJson["order_no"].str)
		];
		return jj.toString();
	}
	
	
	
	
}

